package compare;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import util.StringParser;

import algorithms.LosslessCompressionAlgorithm;

public class CompressionRun 
{
	private List<LosslessCompressionAlgorithm> _algorithms;
	private List<File> _folders;
	private File _results;
	private BufferedWriter _resultsOutCsv;

	public CompressionRun(List<File> folders, List<LosslessCompressionAlgorithm> alogrithms, File results) throws IOException {

		_algorithms = alogrithms;
		_folders = folders;
		_results = results;
	}

	public void start() throws IOException {
		
		_resultsOutCsv = new BufferedWriter(new FileWriter(_results));		
		for (File folder : _folders) {
			compressFolder(folder);
		}
		_resultsOutCsv.close();
	}

	private void compressFolder(File folder) throws IOException {
		
		File[] originals = folder.listFiles();
		for (LosslessCompressionAlgorithm algorithm : _algorithms ) {
			for (File original : originals) {
				File compressed = new File(original.getPath() + "." + algorithm.getFileExtension());
				Compression curCmpr = new Compression(original, compressed,  algorithm);
				curCmpr.compress();
				// filename; segmentation; feature; compression; ratio
				String name = original.getName();
				String result = String.format("%s;%s;%s;%s;%f;%d;%d\n", name, StringParser.getSegmentationAlgorithm(name),
											   StringParser.getFeatureExtractionAlgorithm(name), algorithm.getClass().getName(), curCmpr.getCompressionRatio(),
											   curCmpr.getSizeBefore(), curCmpr.getSizeAfter());
				compressed.delete();
				_resultsOutCsv.write(result);
				_resultsOutCsv.flush();
			}			
		}
	}
}
